<template>
  <div class="employees-container">
    <div class="app-container">
      <page-tools>
        <template #left>
          <span>总记录数: {{ total }} 条</span>
        </template>
        <template #right>
          <el-button type="warning" size="small" @click="$router.push('/import')">excel导入</el-button>
          <el-button type="danger" size="small" @click="handleDownload">excel导出</el-button>
          <el-button type="primary" size="small" @click="showDialog=true">新增员工</el-button>
        </template>
      </page-tools>

      <el-card style="margin-top: 10px;">
        <el-table :data="list" border :default-sort="{prop: 'timeOfEntry', order: 'ascending'}">
          <el-table-column label="序号" type="index" />
          <el-table-column label="姓名" prop="username" />
          <el-table-column label="工号" prop="workNumber" sortable />
          <el-table-column label="聘用形式" prop="formOfEmployment">
            <!-- 自义定表格中的内容调用函数进行格式化 -->
            <template #default="{row}">
              {{ hireTypeFormat(row.formOfEmployment) }}
            </template>
          </el-table-column>
          <el-table-column label="部门" prop="departmentName" />
          <el-table-column label="入职时间" prop="timeOfEntry" sortable />
          <!-- <el-table-column label="账户状态" prop="username"/> -->
          <el-table-column label="操作" width="280">
            <template #default="{row}">
              <!-- <el-button type="text" size="small" @click="$router.push(`/employees/detail?id=${row.id}`)">查看</el-button> -->
              <el-button
                type="text"
                size="small"
                @click="$router.push(`/employees/detail/${row.id}`)"
              >查看</el-button>
              <el-button type="text" size="small" @click="hAssignRole(row.id)">分配角色</el-button>
              <el-button type="text" size="small" @click="hDel(row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <el-row type="flex" justify="center" align="middle" style="height: 60px">
          <el-pagination
            :current-page="page"
            :page-sizes="[2,3,5,10,20]"
            :page-size="size"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </el-row>
      </el-card>
      <!-- 准备新增员工的弹层 -->
      <el-dialog
        title="新增员工"
        :visible.sync="showDialog"
        @close="hClose"
      >
        <empDialog ref="empDialog" @close="showDialog=false" @success="hSuccess" />
      </el-dialog>
      <!-- 分配角色 -->
      <el-dialog title="分配角色" :visible.sync="roleShowDialog">
        <AssignRole
          v-if="roleShowDialog"
          :role-id="roleId"
          @close="roleShowDialog=false"
        />
      </el-dialog>
    </div>
  </div>
</template>
<script>
import AssignRole from './assignRole.vue'
import { getEmployees, delEmployee } from '@/api/employees'
import employeesEnum from '@/constant/employees'
import empDialog from '@/views/employees/empDialog.vue'
// [{id:1,value:'正式'},{id:2,value:'非正式'}]==>{1:'正式',2:'非正式'}
// const hireType = {}
// employeesEnum.hireType.forEach(item => {
//   hireType[item.id] = item.value
// })
// [].reduce(('累计和','数组中的元素','索引号')=>{},'默认值')
const hireType = employeesEnum.hireType.reduce((acc, item) => {
  acc[item.id] = item.value
  return acc
}, {})
export default {
  components: {
    empDialog,
    AssignRole
  },
  data() {
    return {
      roleId: '', // 保存当前角色的id
      list: [],
      page: 1, // 页码值
      size: 5, // 每页显示的条数
      total: 0, // 总条数
      showDialog: false, // 控制新增员工对话框的显示和隐藏
      roleShowDialog: false// 控制分配角色对话框的显示和隐藏
    }
  },
  created() {
    this.loadEmployees()
  },
  methods: {
    // 获取当前角色的id 传递给子组件
    hAssignRole(id) {
      this.roleId = id
      this.roleShowDialog = true
    },
    dataFormat(list) {
      const mapInfo = {
        'id': '编号',
        'password': '密码',
        'mobile': '手机号',
        'username': '姓名',
        'timeOfEntry': '入职日期',
        'formOfEmployment': '聘用形式',
        'correctionTime': '转正日期',
        'workNumber': '工号',
        'departmentName': '部门',
        'staffPhoto': '头像地址'
      }

      const one = list[0]
      // console.log(one)

      let header = []
      if (one) {
        // console.log('Object.keys(one)',Object.keys(one))
        header = Object.keys(one).map(enkeys => {
          // console.log('mapInfo[enkeys]',mapInfo[enkeys])
          return mapInfo[enkeys]
        })
      }

      const data = list.map(item => {
        return Object.values(item)
      })

      // console.log('header',header)
      // console.log('data',data)

      return { header, data }
    },
    async handleDownload() {
      // 1. 发送请求获取数据
      try {
        const res = await getEmployees(this.page, this.size)
        console.log(res)
        if (res.code !== 10000) return
        console.log('res.data.rows', res.data.rows)
        // 2. 需要将获取到的数据转换为excel需要的格式  header, data

        const { header, data } = this.dataFormat(res.data.rows)

        // 3. 调用 excel.export_json_to_excel 将格式化好的数据写入到excel文件中
        // import('@/vendor/Export2Excel') 懒加载的方式读取一个文件（模块）返回是一个promise实例对象
        import('@/vendor/Export2Excel').then(excel => {
          // excel指的是模块对象(文件对象),就可以直接调用文件中的任何函数或者使用文件中的任何变量excel.函数名()  || excel.变量
          console.log(excel, 'excel')

          // excel调用export_json_to_excel()
          excel.export_json_to_excel({
            header: header,
            data,
            filename: this.filename,
            autoWidth: this.autoWidth,
            bookType: this.bookType
          })
        })
      } catch (error) {
        console.log(error)
      }
    },
    // 实现删除员工
    hDel(id) {
      this.$confirm('您确定删除该员工吗???').then(async() => {
        const res = await delEmployee(id)
        console.log(res)
        // 处理删除的特殊情况  当页面只有1条数据的时候 让page减1
        if (this.list.length === 1) {
          this.page--
          if (this.page <= 0) {
            this.page = 1
          }
        }
        this.loadEmployees()
      }).catch(err => err)
    },
    // 重置表单
    hClose() {
      this.$refs.empDialog.resetForm()
    },
    // 关闭弹层,重新渲染数据
    hSuccess() {
      this.total++
      this.page = Math.ceil(this.total / this.size)
      this.loadEmployees()
      this.showDialog = false
    },
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`)
      this.page = 1
      this.size = val
      this.loadEmployees()
    },
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`)
      this.page = val
      this.loadEmployees()
    },
    // 加载员工列表
    async loadEmployees() {
      try {
        const res = await getEmployees(this.page, this.size)
        this.list = res.data.rows
        this.total = res.data.total
      } catch (error) {
        console.log(error)
      }
    },
    // 需求 返回的是 正式和非正式
    hireTypeFormat(data) {
      // data===>1或者2
      // return employeesEnum.hireType.find(item => item.id === data).value
      return hireType[data] || '未知'
    }
  }
}
</script>
